<template>
  <div class="dashboard-container" v-if="this.role == '管理员'">
    <h1>商品管理</h1>
    <div>
      <el-button type="primary" @click="insertButton" style="width: 100px;margin-left: 40px">新增</el-button>
      <el-input placeholder="商品名称" v-model="commodityName" clearable style="width: 200px;margin-left: 40px"/>
      <el-select v-model="type" clearable placeholder="商品类型" style="width: 200px;margin-left: 40px">
        <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value"/>
      </el-select>
      <el-select v-model="state" clearable placeholder="商品状态" style="width: 200px;margin-left: 40px">
        <el-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value"/>
      </el-select>
      <el-button type="primary" @click="selectAll" style="width: 100px;margin-left: 40px">查询</el-button>
      <el-button @click="check" style="width: 100px;margin-left: 40px">重置</el-button>
      <el-table :data="commodityList.slice((currentPage-1)*pageSize,currentPage*pageSize)" height="720px" border style="width: 100%;margin-top: 20px">
        <el-table-column align="center" fixed prop="commodityId" label="商品ID" sortable/>
        <el-table-column align="center" fixed prop="commodityName" label="商品名称" sortable/>
        <el-table-column align="center" fixed label="简介">
          <template v-slot="scope">
            <span style="max-width: 150px;text-overflow: ellipsis; overflow: hidden;white-space: nowrap; ">{{scope.row.synopsis}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed prop="number" label="库存数量" sortable/>
        <el-table-column align="center" fixed prop="price" label="价格" sortable/>
        <el-table-column align="center" fixed prop="type" label="类型" sortable/>
        <el-table-column align="center" fixed prop="locality" label="产地" sortable/>
        <el-table-column align="center" fixed prop="state" label="状态" sortable/>
        <el-table-column prop="imageMain" label="商品图片" sortable align="center" fixed header-align="center">
          <template v-slot="scope">
            <el-image fit="cover" v-if="scope.row.imageMain" style="width: 100%; height: 100px" :src="require ('C:/upload/' + scope.row.imageMain)"
                      :preview-src-list="[require ('C:/upload/' + scope.row.imageMain)]"/>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed label="操作">
          <template v-slot="scope">
            <el-button type="text" v-if="scope.row.imageOther" @click="viewOtherImage(scope.row.imageOther)">
              查看其他图片
            </el-button>
            <el-button type="text" @click="updateButton(scope.row)">修改</el-button>
            <el-button type="text" @click="deleteButton(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="float: right;margin-top: 20px">
        <el-pagination background
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="currentPage"
                       :page-sizes="[5,10,15]"
                       :page-size="pageSize"
                       layout="total,jumper,prev, pager, next,sizes"
                       :total="commodityList.length" >
        </el-pagination>
      </div>
      <el-dialog title="删除" width="40%" :visible.sync="deleteButtonController">
        <h1>请确认是否删除？</h1>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="deleteUser">确定</el-button>
          <el-button @click="deleteButtonController = false">取消</el-button>
        </span>
      </el-dialog>

      <el-dialog :title="this.title" width="40%" :visible.sync="addOrUpdateButtonController" @close="closeDialog('ruleForm')">
        <el-form label-width="20%" :rules="roles" :model="commodity" ref="ruleForm">
          <el-form-item label="商品名称" prop="commodityName">
            <el-input v-model="commodity.commodityName" maxlength="20" show-word-limit style="width: 80%" clearable
                      placeholder="请输入商品名称"
            />
          </el-form-item>
          <el-form-item label="简介" prop="synopsis">
            <el-input v-model="commodity.synopsis" maxlength="60" show-word-limit style="width: 80%" clearable
                      placeholder="请输入简介"
            />
          </el-form-item>
          <el-form-item label="库存数量" prop="number">
            <el-input v-model="commodity.number"  maxlength="20" show-word-limit style="width: 80%" clearable
                      placeholder="请输入库存数量"
            />
          </el-form-item>

          <el-form-item label="价格" prop="price">
            <el-input v-model="commodity.price" maxlength="20" show-word-limit style="width: 80%" clearable
                      placeholder="请输入价格"
            />
          </el-form-item>

          <el-form-item label="类型" prop="">
            <el-select v-model="commodity.type" clearable placeholder="请选择类型" style="width: 80%">
              <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>

          <el-form-item label="产地" prop="locality">
            <el-input v-model="commodity.locality" maxlength="60" show-word-limit style="width: 80%" clearable
                      placeholder="请输入产地"
            />
          </el-form-item>

          <el-form-item label="状态" prop="">
            <el-select v-model="commodity.state" clearable placeholder="请选择商品状态" style="width: 80%">
              <el-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-form>
        <div>
          <div style="display: inline-block;width: 20%;margin-left: 20%">
            <el-upload
              class="upload-demo"
              ref="upload1"
              :action="action"
              :on-success="uploadSuccess1"
              :on-error="uploadError"
              :file-list="fileList"
              :show-file-list="false"
              :auto-upload="true"
              accept="image/jpg,image/jpeg,image/png,image/gif"
            >
              <el-button size="small" type="primary">选择主要图片</el-button>
            </el-upload>
          </div>

          <div style="display: inline-block;width: 20%;margin-left: 20%">
            <el-upload
              class="upload-demo"
              ref="upload2"
              :action="action"
              :on-success="uploadSuccess2"
              :on-error="uploadError"
              :file-list="fileList"
              :show-file-list="false"
              :auto-upload="true"
              accept="image/jpg,image/jpeg,image/png,image/gif"
            >
              <el-button size="small" type="primary">选择其他图片</el-button>
            </el-upload>
          </div>
        </div>
        <div style="margin-top: 20px;text-align: left;margin-left: 60%">
          <el-button v-if="this.commodity.imageOther" @click="deleteImageOther()"
                     size="small" type="primary">清除已上传的其他图片</el-button>
        </div>
        <div style="margin-top: 20px;text-align: center;">
            <span  style="font-size: 20px">已上传其他图片 <span style="font-size: 24px;color: blue">{{ this.otherImageNumber }}</span> 张，
              最多可支持上传 <span style="font-size: 24px;color: red">10</span> 张</span>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="insertOrUpdateCommodity('ruleForm')">确定</el-button>
          <el-button @click="closeDialog('ruleForm')">取消</el-button>
        </span>
      </el-dialog>

      <el-dialog title="查看其他图片" :visible.sync="viewOtherImageButton" @close="viewOtherImageButton = false">
        <!-- 遍历图片路径数组 display: inline-block 设置为弹性布局且自动排列 -->
        <div style="overflow-y: scroll;height: 500px">
          <div v-for="image in imageList" class="block"
               style="display: inline-block;width: 45%;margin-left: 4%;margin-top:  4%"
          >
            <el-image fit="cover" :src="require ('C:/upload/' + image)"/>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="viewOtherImageButton = false">关闭</el-button>
          </span>
      </el-dialog>
    </div>
  </div>
  <div class="dashboard-container" v-else>
    <h1>无权限访问</h1>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { deleteById, insertCommodity, queryAllCommodity, updateCommodity } from '@/api/commodity'

export default {
  name: 'commodity',
  computed: { ...mapGetters(['userId', 'name', 'role']) },
  // 存放页面参数
  data() {
    return {
      // 分页参数
      currentPage: 1,
      pageSize: 5,
      fileList: [],
      action: process.env.VUE_APP_BASE_API + '/file/upload',
      commodityName: '',
      type: '',
      typeList: [
        { value: '服装', label: '服装' },
        { value: '电器', label: '电器' },
        { value: '日用品', label: '日用品' },
        { value: '食品', label: '食品' },
        { value: '玩具', label: '玩具' },
        { value: '珠宝礼品', label: '珠宝礼品' },
        { value: '数字产品', label: '数字产品' }
      ],
      state: '',
      stateList: [
        { value: '上架中', label: '上架中' },
        { value: '已下架', label: '已下架' }
      ],
      commodityList: [],
      addOrUpdateButtonController: false,
      viewOtherImageButton: false,
      otherImageNumber: 0,
      commodity: {
        commodityId:'',
        commodityName: '',
        synopsis: '',
        number: 0,
        price: 0,
        type: '',
        imageMain: '',
        imageOther: '',
        locality: '',
        state: ''
      },
      imageList: [],
      title: '',
      deleteButtonController: false,
      commodityId: '',
      roles: {
        commodityName:
          [{ required: true, trigger: 'blur', message: '商品名称不能为空' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
        synopsis:
          [{ required: true, trigger: 'blur', message: '简介不能为空' },
            { min: 1, max: 60, message: '长度在 1 到 60 个字符', trigger: 'blur' }
            ],
        number:
          [{ required: true, trigger: 'blur', message: '数量不能为空' },
            { pattern:  /^-?\d+$/, message: '只能输入整数', trigger: 'blur' }],
        price:
          [{ required: true, trigger: 'blur', message: '价格不能为空' },
            { pattern:  /^\d+(\.\d*)?$/, message: '只能输入数字', trigger: 'blur' }],
        locality:
          [{ required: true, trigger: 'blur', message: '产地不能为空' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }]
      }
    }
  },
  // 页面初始化加载的方法
  mounted() {
    this.selectAll()
  },
  // 页面的方法和事件
  methods: {
    // 翻页
    handleSizeChange: function (size) {
      this.pageSize = size;
    },
    // 翻页
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage;
    },
    viewOtherImage(images) {
      this.imageList = []
      for (let i = 0; i < Math.min(images.length, 10); i++) {
        this.imageList.push(images[i])
      }
      this.viewOtherImageButton = true
    },
    uploadSuccess1(response) {
      if (response === 'error') {
        this.$message.error('上传图片失败，请重试')
      }
      this.commodity.imageMain = response
      this.fileList = []
    },
    uploadSuccess2(response) {
      if (response === 'error' || this.otherImageNumber >= 10) {
        this.$message.error('上传图片失败或超过10张图片，请重试')
      }
      if (this.commodity.imageOther == null || this.commodity.imageOther == '') {
        this.commodity.imageOther = response
      } else {
        this.commodity.imageOther = this.commodity.imageOther + ';' + response
      }
      this.otherImageNumber = this.otherImageNumber + 1
      this.fileList = []
    },
    uploadError() {
      this.$message.error('上传失败')
      this.fileList = []
    },
    insertButton() {
      this.addOrUpdateButtonController = true
      this.commodity = {
        commodityId: null,
        commodityName: '',
        synopsis: '',
        number: 0,
        price: 0,
        type: '',
        imageMain: '',
        imageOther: '',
        locality: '',
        state: ''
      }
      this.otherImageNumber = 0
      this.title = '新增'
    },
    updateButton(row) {
      this.addOrUpdateButtonController = true
      let imageOthers = null
      if(row.imageOther != null && row.imageOther != ''){
        for (let i = 0; i < row.imageOther.length;i++){
          if(i == 0){
            imageOthers = row.imageOther[i]
          }else {
            imageOthers = imageOthers + ';' +row.imageOther[i]
          }
        }
      }
      this.commodity = {
        commodityId: row.commodityId,
        commodityName: row.commodityName,
        synopsis: row.synopsis,
        number: row.number,
        price: row.price,
        type: row.type,
        imageMain: row.imageMain,
        imageOther: imageOthers,
        locality: row.locality,
        state: row.state,
      }
      this.otherImageNumber = row.imageOther.length
      this.title = '修改'
    },
    deleteImageOther(){
      this.otherImageNumber = 0
      this.commodity.imageOther = ''
    },
    insertOrUpdateCommodity(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.commodity.imageMain == '' || this.commodity.imageMain == null){
            this.$message.error('至少选择一张主要图片')
          }else {
            if(this.title == '新增'){
              insertCommodity(this.commodity).then(
                response => {
                  this.selectAll()
                  this.addOrUpdateButtonController = false
                })
            }else {
              updateCommodity(this.commodity).then(
                response => {
                  this.selectAll()
                  this.addOrUpdateButtonController = false
                }
              )
            }
          }
        } else {
          return false
        }
      })
    },
    selectAll() {
      queryAllCommodity({
        commodityName: this.commodityName,
        type: this.type,
        state: this.state
      }).then(
        response => {
          this.commodityList = response.data
          this.commodityList.find(item => {
            if (item.imageOther != null) {
              item.imageOther = item.imageOther.split(';')
            }
          })
        }
      )
    },
    check() {
      this.commodityName = ''
      this.type = ''
      this.state = ''
      this.selectAll()
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields()
      this.addOrUpdateButtonController = false
      this.viewOtherImageButton = false
    },
    deleteButton(row) {
      this.deleteButtonController = true
      this.commodityId = row.commodityId
    },
    deleteUser(formName) {
      deleteById({
        commodityId: this.commodityId
      }).then(
        response => {
          this.deleteButtonController = false
          this.commodityId = ''
          this.selectAll()
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
